<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" label-width="68px">
      <el-form-item label="字典名称" prop="dictLabel">
        <el-input
          v-model="queryParams.dictLabel"
          placeholder="请输入字典名称"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="所属类型" prop="dictTypeId">
        <el-select v-model="queryParams.dictTypeId"
                   placeholder="字典类型"
                   clearable
                   size="small"
        >
          <el-option v-for="dictType in dictTypeOptions"
                     :key="dictType.dictId"
                     :label="dictType.dictName"
                     :value="dictType.dictId"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select
          v-model="queryParams.status"
          placeholder="状态"
          clearable
          size="small"
        >
          <el-option
            v-for="dict in statusOptions"
            :key="dict.dictValue"
            :label="dict.dictLabel"
            :value="dict.dictValue"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery"
                   v-hasPermi="['baseData:dictData:query']"
        >搜索
        </el-button>
        <el-button type="primary" icon="el-icon-plus" size="mini" @click="handleAdd"
                   v-hasPermi="['baseData:dictData:add']"
        >新增
        </el-button>
        <el-button type="warning" icon="el-icon-download" size="mini" v-hasPermi="['baseData:dictData:export']"
                   @click="handleExport"
        >导出
        </el-button>
      </el-form-item>
    </el-form>

    <el-table v-loading="loading" :data="dictDataList" border>
      <el-table-column label="字典名称" align="center" prop="dictLabel"/>
      <el-table-column label="字典值" align="center" prop="dictValue"/>
      <el-table-column label="所属类型" align="center" prop="dictTypeName"/>
      <el-table-column label="是否默认" align="center" prop="isDefault" v-if="false"/>
      <el-table-column label="状态" align="center" prop="status" :formatter="statusFormat"/>
      <el-table-column label="显示排序" align="center" prop="dictSort"/>
      <el-table-column label="创建时间" align="center" prop="createTime" width="160"/>
      <el-table-column label="备注" align="center" prop="remark" :show-overflow-tooltip="true"/>
      <el-table-column label="操作" align="center" width="150">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['baseData:dictData:edit']"
          >修改
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['baseData:dictData:remove']"
          >删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getDictDataList"
    />

    <!-- 添加或修改对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="600px" append-to-body :before-close="closeDialogConfirm">
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="字典类型" prop="dictTypeId">
          <el-select v-model="form.dictTypeId"
                     placeholder="字典分类"
                     size="small"
          >
            <el-option v-for="item in dictTypeOptions"
                       :key="item.dictId"
                       :label="item.dictName"
                       :value="item.dictId"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="字典名称" prop="dictLabel">
          <el-input v-model="form.dictLabel" placeholder="请输入字典名称"/>
        </el-form-item>
        <el-form-item label="字典值" prop="dictValue">
          <el-input v-model="form.dictValue" placeholder="请输入字典值"/>
        </el-form-item>
        <el-form-item label="显示排序" prop="dictSort">
          <el-input-number v-model="form.dictSort" controls-position="right" :min="0"/>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="form.status">
            <el-radio
              v-for="dict in statusOptions"
              :key="dict.dictValue"
              :label="dict.dictValue"
            >{{ dict.dictLabel }}
            </el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入内容"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  addDictData,
  deleteDictData, exportDictData,
  getDictDataByType,
  listDictData,
  listDictType,
  updateDictData
} from '@/api/system/dict'
import { getOrderNumOfList } from '@/utils/ruoyi'

export default {
  name: 'index',
  data() {
    return {
      // 遮罩层
      loading: true,
      // 总条数
      total: 0,
      // 字典表格数据
      dictDataList: [],
      // 所有字典数据
      allDictDataList: [],
      // 弹出层标题
      title: '',
      // 是否显示弹出层
      open: false,
      // 状态数据字典
      statusOptions: [],
      // 字典类型
      dictTypeOptions: [],
      // add/update
      operationType: '',
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        dictLabel: undefined,
        dictTypeId: undefined,
        status: undefined
      },
      // 表单参数
      form: {
        dictTypeId: undefined
      },
      rules: {
        dictTypeId: [
          { required: true, message: '所属分类不能为空', trigger: 'blur' }
        ],
        dictLabel: [
          { required: true, message: '字典名称不能为空', trigger: 'blur' }
        ],
        dictValue: [
          { required: true, message: '字典值不能为空', trigger: 'blur' }
        ],
        dictSort: [
          { required: true, message: '显示排序不能为空', trigger: 'blur' }
        ]
      }
    }
  },
  created() {
    this.getDictDataList()
    getDictDataByType('sys_normal_disable').then(response => {
      this.statusOptions = response.data
    })
    listDictType({ status: 0 }).then(response => {
      this.dictTypeOptions = response.rows
    })
  },
  watch: {
    'form.dictTypeId': {
      handler(value) {
        if (this.operationType === 'add') {
          if (value) {
            const filterList = this.allDictDataList.filter(item => item.dictTypeId === value)
            this.form.dictSort = getOrderNumOfList(filterList, 'dictSort')
          }
        }
      }
    }
  },
  methods: {
    getDictDataList() {
      this.loading = true
      listDictData(this.queryParams).then(response => {
        this.dictDataList = response.rows
        this.total = response.total
        this.loading = false
      })

      listDictData().then(response => {
        this.allDictDataList = response.rows
      })
    },
    // 字典状态字典翻译
    statusFormat(row, column) {
      return this.selectDictLabel(this.statusOptions, row.status)
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    // 表单重置
    reset() {
      this.form = {
        dictLabel: undefined,
        dictValue: undefined,
        dictSort: undefined,
        dictTypeId: undefined,
        isDefault: undefined,
        status: '0',
        remark: undefined
      }
      this.resetForm('form')
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getDictDataList()
    },
    handleAdd() {
      this.reset()
      this.operationType = 'add'
      this.open = true
      this.title = '添加字典数据'
      this.form.dictSort = 1
    },
    handleUpdate(row) {
      this.reset()
      this.operationType = 'update'
      this.open = true
      this.title = '修改字典数据'

      const selectedDictData = this.dictDataList.find(item => {
        return item.dictCode === row.dictCode
      })
      if (selectedDictData) {
        this.form = { ...selectedDictData }
      }
    },
    handleDelete(row) {
      this.$confirm('是否删除字典"' + row.dictLabel + '"?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        deleteDictData(row.dictCode).then(response => {
          this.getDictDataList()
        })
      }).then(() => {
        this.msgSuccess('删除成功')
      })
    },
    /** 提交表单 */
    submitForm() {
      if (this.form.remark && this.form.remark.indexOf('^&') > 0) {
        this.msgError(`备注不能含有'^&'`)
      } else {
        this.$refs['form'].validate(valid => {
          if (valid) {
            if (this.operationType === 'add') {
              addDictData(this.form).then(response => {
                if (response.code === 200) {
                  this.msgSuccess('添加成功')
                  this.open = false
                  this.getDictDataList()
                }
              })
            }
            if (this.operationType === 'update') {
              updateDictData(this.form).then(response => {
                if (response.code === 200) {
                  this.msgSuccess('修改成功')
                  this.open = false
                  this.getDictDataList()
                }
              })
            }
          }
        })
      }
    },

    /**
     * 对话框确认关闭
     */
    closeDialogConfirm() {
      this.$confirm('确认关闭?').then(() => {
        this.open = false
      }).catch(() => {
      })
    },

    /** 导出按钮操作 */
    handleExport() {
      this.$confirm('是否确认导出?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        return exportDictData(this.queryParams)
      }).then(response => {
        this.download(response.msg)
      }).catch(function() {
      })
    }
  }
}
</script>

<style scoped>

</style>
